package algorithm.graph.adjacencylist;

import java.util.Arrays;
import java.util.stream.IntStream;

public class AdjacencyListGraph {
    private Node[] nodeArray;
    private boolean isDirected;

    public AdjacencyListGraph(int nodeLength) {
        this(nodeLength, false);
    }

    public AdjacencyListGraph(int nodeLength, boolean isDirected) {
        this.nodeArray = new Node[nodeLength];
        this.isDirected = false;
        for (int i = 0; i < this.nodeArray.length; i++) {
            this.nodeArray[i] = new Node(i);
        }
    }

    public AdjacencyListGraph addEdge(int start, int second) {
        if (this.isDirected) {
            nodeArray[start].getEdgeList().add(new Edge(start, second));
        } else {
            nodeArray[start].getEdgeList().add(new Edge(start, second));
            nodeArray[second].getEdgeList().add(new Edge(second, start));
        }
        return this;
    }

    public boolean isConnectedGraph() {
        UnionFindSet unionFindSet = new UnionFindSet(nodeArray.length);
        Arrays.stream(nodeArray).forEach(from -> {
            from.getEdgeList().forEach(to -> {
                unionFindSet.merge(from.getIndex(), to.getTo());
            });
        });
        int size = unionFindSet.getGroupSize();
        return size <= 1;
    }

    public Node[] getNodeArray(){
        return this.nodeArray;
    }

    public boolean isDirected() {
        return isDirected;
    }
}
